/*
 * graph.c
 *
 *  Created on: 05/11/2010
 *      Author: dela
 */

#include "graph.h"
#include "node.h"
#include <malloc.h>

/**
 *
 */
void graph_destroy( TGraph *graph ) {
	TNode *n;
	while ( !ls_Vacia(graph->nodes) ) {
		ls_ElemCorriente(graph->nodes, (void**)&n);
		node_destroy(n);
		ls_BorrarCorriente(&(graph->nodes));
	}
}

/**
 *
 */
void graph_reset( TGraph *graph ) {
	TNode *n;
	if ( ls_MoverCorriente( &(graph->nodes), LS_PRIMERO ) ) {
		do {
			ls_ElemCorriente(graph->nodes, (void**)&n);
			node_reset(n);
		} while ( ls_MoverCorriente( &(graph->nodes), LS_SIGUIENTE ) );
	}
}

/**
 *
 */
void generateNewNode( TNode **node, int id ) {
	*node = malloc( sizeof(TNode) );
	(*node)->id = id;
	(*node)->type = NODO_PERSON;
	ls_Crear( &((*node)->nodes) );
	ls_Crear( &((*node)->ids) );
}

/**
 *
 */
void graph_getPersonNode( TGraph *graph, TNode **node, int id ) {
	if ( ls_Vacia( graph->nodes ) ) {
		generateNewNode( node, id );
		ls_Insertar( &(graph->nodes), LS_PRIMERO, *node );
	} else {
		TNode *aux;
		ls_MoverCorriente( &(graph->nodes), LS_PRIMERO );
		ls_ElemCorriente( graph->nodes, (void**)&aux );
		while ( !( (aux->id == id) && (aux->type == NODO_PERSON) ) && ls_MoverCorriente( &(graph->nodes), LS_SIGUIENTE ) ) {
			ls_ElemCorriente( graph->nodes, (void**)&aux );
		}
		if ( aux->id == id && aux->type == NODO_PERSON ) {
			*node = aux;
		} else {
			generateNewNode( node, id );
			ls_Insertar( &(graph->nodes), LS_PRIMERO, *node );
		}
	}
}
